package task

import (
	"time"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/event"
	time2 "xr-game-server/core/xrtime"
	"xr-game-server/dao/taskdao"
	"xr-game-server/gamecfg"
	"xr-game-server/gameevent"
)

func initReset() {
	event.Sub(gameevent.RoleEnterGameEvent, onDayEvent)
}

func onDayEvent(data any) {
	eventData := data.(*gameevent.RoleEnterGameEventData)
	initAllTask(eventData.RoleId)
	timeData := taskdao.GetTaskResetTime(eventData.RoleId)
	if timeData.DayTime != nil && !time2.IsSameDay(*timeData.DayTime, time.Now()) {
		//开始重置按天的任务
		resetParam(eventData, gamecfg.DayTaskReSet)
	}
	if timeData.WeekTime != nil && !time2.IsSameWeek(*timeData.WeekTime, time.Now()) {
		//开始重置按周的任务
		resetParam(eventData, gamecfg.WeekTaskReset)
	}
}

func resetParam(event *gameevent.RoleEnterGameEventData, timeType int) {
	tasks := taskdao.GetTasksByRoleId(event.RoleId)
	for _, task := range tasks {
		taskCfg := gamecfg.GetTaskById(task.TaskCfgId)
		if taskCfg.TimeHandler == timeType {
			task.SetStatus(Tasking)
			task.SetUpdatedAt(time.Now())
			taskDetails := taskdao.GetTaskDetailsByTaskId(task.ID)
			for _, taskDetail := range taskDetails {
				taskDetail.SetVal(common.Zero)
				taskDetail.SetUpdatedAt(time.Now())
			}
		}
	}
}
